package com.example.mybank.springSecurity;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybank.mapper.UsersMapper;
import com.example.mybank.entity.Users;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service("userDetailsService")
public class MyUserDetailsService extends Users implements UserDetailsService {
    @Autowired
    private UsersMapper usersMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("username:"+username+"结束");
        //调用usersMapper方法，根据用户名查询数据库
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        List<Users> users1 = usersMapper.selectList(wrapper);
        Users users = users1.size()==0?null:users1.get(0);

        //判断
        if(users==null){//数据库没有数据，认证失败
            throw new UsernameNotFoundException("用户名不存在！");
        }
        log.info("loadUserByUsername:"+users.toString());


        return new UserHandler(users);

        //手动设置了role，也可以通过数据库查询获取
//        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(
//                users.getIs_admin().equals(true)?"admin":"users");  //配置角色

//        return new User(users.getUsername(),
//                new BCryptPasswordEncoder().encode(users.getPassword()),auths);
    }
}
